package com.bookmanager.www.service.impl;

import cn.hutool.core.util.IdUtil;
import com.bookmanager.www.entity.FlBook;
import com.bookmanager.www.entity.FlCarts;
import com.bookmanager.www.mapper.FlBookMapper;
import com.bookmanager.www.mapper.FlCartsMapper;
import com.bookmanager.www.service.FlCartsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 用户购物车 服务实现类
 * </p>
 *
 * @author 风离
 * @since 2021-09-17
 */
@Service
public class FlCartsServiceImpl extends ServiceImpl<FlCartsMapper, FlCarts> implements FlCartsService {

    @Resource
    FlCartsMapper flCartsMapper;
    @Resource
    FlBookMapper flBookMapper;
    @Override
    public List<FlCarts> selectCartsByUserId(String userId) {

        List<FlCarts> carts = flCartsMapper.selectCartsByUserId(userId);

        return carts;
    }

    @Override
    public int createCartForUser(String userId, String bookId, int count) {

        LocalDateTime createdTimestamp = LocalDateTime.now();
        LocalDateTime updatedTimestamp = LocalDateTime.now();

        //生成唯一购物车id
        String cartsId = IdUtil.objectId();
        System.out.println("传入的UserId为====>"+userId);
        int insert = flCartsMapper.createCartForUser(cartsId,userId,bookId,count,createdTimestamp,updatedTimestamp);

        return insert;
    }

    @Override
    public int addBookToCarts(String userId, String bookId, int count) {
        LocalDateTime createdTimestamp = LocalDateTime.now();
        LocalDateTime updatedTimestamp = LocalDateTime.now();
        //生成唯一购物车id
        String cartsId = IdUtil.objectId();

        int insert = flCartsMapper.addBookToCarts(cartsId,userId,bookId,count,createdTimestamp,updatedTimestamp);

        return insert;
    }

    @Override
    public double getAllCartsPrice(String userId) {
        List<FlCarts> flCartsList =flCartsMapper.selectCartsByUserId(userId);
        double total = 0;
        for (int i =0;i<flCartsList.size();i++)
        {
            int bookCount =  flCartsList.get(i).getCount();
            String bookId = flCartsList.get(i).getBookId();
            int checked = flCartsList.get(i).getChecked();
            FlBook book= flBookMapper.selectBookByBookId(bookId);
            String bookPrice = book.getPrice();
            double temp  = Double.valueOf(bookPrice);
            //没选中不计入总价格中
            if (checked!=1)
            {
                temp=0;
            }
            total+=bookCount*temp;
        }
        //构造方法的字符格式这里如果小数不足2位,会以0补足.
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        String strPrice = decimalFormat.format(total);
        double price =Double.parseDouble(strPrice);

        return price;
    }


}
